<template>
  <div class="p-2 page-flex">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目名称" prop="proName">
              <el-input v-model="queryParams.proName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目编号" prop="proNumber">
              <el-input v-model="queryParams.proNumber" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类型" prop="proType">
              <el-select v-model="queryParams.proType" placeholder="请选择项目类型" clearable>
                <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目状态" prop="proStatus">
              <el-select v-model="queryParams.proStatus" placeholder="请选择项目状态" clearable>
                <el-option v-for="dict in contract_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目负责人" prop="proLeadersId" label-width="82px">
              <el-select
                :model-value="selectedSearchLeader ? selectedSearchLeader.userName || selectedSearchLeader.nickName : ''"
                placeholder="请选择项目负责人" style="width: 226px" clearable @click="showSearchLeaderSelector = true"
                @clear="clearSearchLeader">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchLeaderSelector = true"> 选择项目负责人 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="执行总裁" prop="proPresidentsId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择项目执行总裁" style="width: 240px" clearable @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择项目执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="projectList" border class="flex-table">
        <el-table-column label="项目名称" align="center" prop="proName" min-width="150" show-overflow-tooltip />
        <el-table-column label="项目编号" align="center" prop="proNumber" min-width="120" />
        <el-table-column label="项目类型" align="center" prop="proType" min-width="100">
          <template #default="scope">
            <dict-tag :options="project_type" :value="scope.row.proType || ''" />
          </template>
        </el-table-column>
        <el-table-column label="项目金额" align="center" prop="proAmount" min-width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.proAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="项目状态" align="center" prop="proStatus" width="150">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.proStatus || ''" />
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" width="150" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="150">
          <template #default="scope">
            {{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link class="weeklog-button" @click="handleWeekLog(scope.row)">
              <el-icon>
                <Edit />
              </el-icon>
              <span>周总结填写</span>
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无项目数据" />
        </template>
      </el-table>

      <pagination class="pagination-fixed" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 项目负责人选择对话框 -->
    <UserSelector v-model:visible="showSearchLeaderSelector" title="选择项目负责人" :multiple="false"
      :selectedUserIds="queryParams.proLeadersId" :selectedUserNames="selectedSearchLeaderName"
      @confirmWithIds="handleSearchLeaderConfirm" @cancel="handleSearchLeaderCancel" />

    <!-- 项目执行总裁选择对话框 -->
    <UserSelector v-model:visible="showSearchPresidentSelector" title="选择项目执行总裁" :multiple="false"
      :selectedUserIds="queryParams.proPresidentsId" :selectedUserNames="selectedSearchPresidentName"
      @confirmWithIds="handleSearchPresidentConfirm" @cancel="handleSearchPresidentCancel" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';
import { weekLogPageList } from '@/api/project/init/proInfo';
import { useRouter } from 'vue-router';
import { Edit } from '@element-plus/icons-vue';
import UserSelector from '@/components/UserSelector/index.vue';

const { proxy } = getCurrentInstance();
const router = useRouter();
const { project_type, contract_status } = toRefs<any>(proxy?.useDict('project_type', 'contract_status'));

const loading = ref(false);
const showSearch = ref(true);
const projectList = ref([]);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
// 搜索相关的状态变量（负责人/执行总裁 选择器）
const selectedSearchLeader = ref<any>(null);
const selectedSearchLeaderName = ref('');
const showSearchLeaderSelector = ref(false);
const selectedSearchPresident = ref<any>(null);
const selectedSearchPresidentName = ref('');
const showSearchPresidentSelector = ref(false);

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  proName: undefined,
  proNumber: undefined,
  proType: undefined,
  proStatus: undefined,
  proLeadersId: undefined,
  proPresidentsId: undefined,
  params: {}
});

const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00';
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    // 使用工具方法处理创建时间范围（between）
    proxy?.addDateRange(params, dateRange.value, 'CreateTime');
    const res = await weekLogPageList(params);
    projectList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    ElMessage.error('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {};
  // 重置负责人/执行总裁
  selectedSearchLeader.value = null;
  selectedSearchLeaderName.value = '';
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  (queryParams.value as any).proLeadersId = undefined;
  (queryParams.value as any).proPresidentsId = undefined;
  handleQuery();
};

const handleWeekLog = (row) => {
  // TODO: 跳转到周总结填写页面
  router.push(`/project/weeklog-edit/index/${row.id}`);
};

// 负责人/执行总裁 选择器回调与清理
const handleSearchLeaderConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchLeader.value = data.users[0];
    selectedSearchLeaderName.value = data.userNames || '';
    queryParams.value.proLeadersId = data.userIds || '';
  } else {
    selectedSearchLeader.value = null;
    selectedSearchLeaderName.value = '';
    queryParams.value.proLeadersId = undefined;
  }
  showSearchLeaderSelector.value = false;
};

const handleSearchLeaderCancel = () => {
  showSearchLeaderSelector.value = false;
};

const clearSearchLeader = () => {
  selectedSearchLeader.value = null;
  selectedSearchLeaderName.value = '';
  queryParams.value.proLeadersId = undefined;
};

const handleSearchPresidentConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchPresident.value = data.users[0];
    selectedSearchPresidentName.value = data.userNames || '';
    queryParams.value.proPresidentsId = data.userIds || '';
  } else {
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    queryParams.value.proPresidentsId = undefined;
  }
  showSearchPresidentSelector.value = false;
};

const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  queryParams.value.proPresidentsId = undefined;
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
/* 页面弹性布局 */
.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

.pagination-fixed {
  margin-top: 8px;
}
</style>

<style lang="scss" scoped>
.weeklog-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;

  .el-icon {
    font-size: 16px;
  }
}
</style>
